const mongoose = require('mongoose')
const Saler = mongoose.model('saler')
const { formatBody } = require('../tools')

module.exports = {
  /**
   * 获取销售列表
   */
  async list (ctx) {
    let page = ctx.query.page || 1
    let limit = ctx.query.limit || 20
    let keyword = ctx.query.keyword || ''
    let list = await Saler.find({
        nickname: { $regex: keyword, $options: '$i' }
      }, { nickname: 1, qq: 1, email: 1, weixin: 1, desc: 1 })
      // .sort({ 'createAt': -1 })
      .limit(+limit).skip(+limit * (+page - 1))
    let total = await Saler.countDocuments()
    return ctx.body = formatBody(1, 'ok', { total, list })
  },
  /**
   * 添加销售
   */
  async create (ctx) {
    let { nickname, qq, email, weixin, desc} = ctx.request.query
    if (!nickname || !qq || !email || !desc) {
      return ctx.body = formatBody(0, '昵称，qq，邮箱，说明不能为空')
    }
    let hasSaler = await Saler.findOne({ qq })
    if (hasSaler) return ctx.body = formatBody(0, '此销售已存在')
    let saler = new Saler({ nickname, qq, email, weixin, desc })
    await saler.save()
    return ctx.body = formatBody(1, '创建成功')
  },
  /**
   * 修改
   */
  
  async update (ctx) {
    let {
      _id,
      nickname,
      email,
      qq,
      weixin,
      desc
    } = ctx.request.body
    const saler = await Saler.findOne({ _id })
    if (saler) {
      await Saler.update({
        _id
      }, {
        nickname, qq, email, weixin, desc
      })
      return ctx.body = formatBody(1, '更新成功')
    }
    return ctx.body = formatBody(1, '不存在该记录，无法进行更新操作')
  },
  /**
   * 删除
   */
  async remove (ctx) {
    let _id = ctx.query._id
    await Saler.deleteOne({_id})
    return ctx.body = formatBody(1, 'ok')
  },
}
